<?php
class Arrival_m extends CI_Model {

	/**
	 * Constructor
	 * @access public
	 * @return void
	 */
    function __construct()
    {
        parent::__construct();
    }

    /**
     * Gets the list of instrumented methods
     * @access public
     * @return array
     */
	function get_methods()
	{
		$this->db->select('method');
		$this->db->distinct();
		$query = $this->db->get('arrival_rate');
		
		if($query->num_rows > 0){
			$methods = array();
			$methods['all'] = 'all methods';
			foreach($query->result() as $row){
				$methods[$row->method] = $row->method;
			}
			
			return $methods;
		} else {
			return false;
		}
	}
	
	/**
	 * Returns the first and last instrumentation times since
	 * the measurements have started.
	 * @access public
	 * @return array
	 */
	function get_min_max_time()
	{
		$this->db->select_max('microtime');
		$maxQuery = $this->db->get('arrival_rate');
		
		if($maxQuery->num_rows == 0) return false;
		
		$this->db->select_min('microtime');
		$minQuery = $this->db->get('arrival_rate');
		
		if($minQuery->num_rows == 0) return false;
		
		return array('minTime' => $minQuery->row()->microtime,
					 'maxTime' => $maxQuery->row()->microtime);
	}
	
	/**
	 * Gets the last instrumented date and time minus 24hours
	 * @return int
	 */
	function get_last_time()
	{
		$this->db->select_max('microtime');
		$maxQuery = $this->db->get('arrival_rate');
		
		if($maxQuery->num_rows == 0) return false;
		
		$time = explode(".", $maxQuery->row()->microtime);
		
		return $time[0]-84600;
	}
	
	/**
	 * Returns the instrumented data for the given parameters.
	 * @param int $requests
	 * @param int $over
	 * @param int $from
	 * @param String $method
	 * @return The number of requests
	 */
	function get_data($from, $to, $method)
	{
		
		//If a specific query is requested, perform it, else return default
		if(!empty($from) && !empty($to) && !empty($method))
		{
			//Add condition for method
			if($method != 'all' && count(explode("::", $method)) > 0){
				$method = " AND method = '$method' ";
			} else {
				$method = null;
			}
			
			//Decrease/Increase the time value to include everything
			$from = $from - 1;
			$to = $to + 1;
			$query = "SELECT count(id) as requests 
							   		   FROM arrival_rate 
							   		   WHERE microtime > '$from' AND microtime <= '$to'" . $method;
			
			$query = $this->db->query($query);
			
		} else {

			$from = time() - 84600;
			$to = time();
			//Get the last 24h measurements over 0.5 seconds by default
			$query = $this->db->query("SELECT count(id) as requests 
														FROM arrival_rate
														WHERE microtime > '$from' AND microtime < '$to'");
		}
		
		//There will always be a query returned
		return $query->row()->requests;
		
	}
	
}

//EOF arrival_m.php